package com.zhaokuner.parentstarter.utils;

import com.zhaokuner.parentstarter.exception.BusinessException;
import lombok.extern.log4j.Log4j2;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;

import javax.validation.ConstraintViolation;
import javax.validation.Validator;
import java.util.Set;

/**
 * 类描述:验证工具类
 *
 * @author 赵希坤 zhaoxikun
 * @date 2020/12/10 19:25
 */
@Log4j2
public class ValidatorUtil {


    /**
     * 验证器
     */
    private static Validator validator;

    @Autowired
    public void setValidator(Validator validator) {
        ValidatorUtil.validator = validator;
    }


    /**
     * 验证 并 抛异常
     *
     * @param ao  ao
     * @param <T> ao
     */
    public static <T> void validatorThrowException(T ao) {
        String error = ValidatorUtil.validator(ao);
        if (StringUtils.isNotBlank(error)) {
            String msg = String.format("参数验证失败：error:%s req(%s):%s", error, null != ao ? ao.getClass().getName() : null, JacksonUtils.toJson(ao));
            BusinessException exception = new BusinessException(error);
            log.info(msg, exception);
            throw exception;
        }
    }

    /**
     * 验证 并 返回验证信息
     *
     * @param ao  ao
     * @param <T> ao
     * @return null 通过，not null 有问题
     */
    public static <T> String validator(T ao) {
        if (null == ao) {
            return "数据对象不可为空";
        }
        Set<ConstraintViolation<T>> set = validator.validate(ao);
        if (set.isEmpty()) {
            return null;
        }
        String msg = null;
        for (ConstraintViolation<T> constraintViolation : set) {
            msg = constraintViolation.getMessage();
        }
        return msg;
    }

}
